package com.hlju.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hlju.reggie.bean.User;
import com.hlju.reggie.common.R;
import com.hlju.reggie.common.ValidateCodeUtils;
import com.hlju.reggie.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    //发送短信验证码
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request) {
        //获取传递过来的手机号
        String phone = user.getPhone();
        //非空判断
        if (StringUtils.isNotEmpty(phone)) {
            //生成一个随机的验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            System.out.println("生成的验证码====>" + code);
            //调用阿里云发送短信
            //SMSUtils.sendMessage("ABC商城","SMS_463600053",phone,code +"");
            //将生成的验证码存入到session中
            //request.getSession().setAttribute("code",code + "");
            //将生成的验证码存入到Redis中 key:phone value：code
            redisTemplate.opsForValue().set(phone, code + "", 5, TimeUnit.MINUTES);
            return R.sucess("短信验证码发送成功");
        }
        return R.error("短信验证码发送失败");
    }

    //登录
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpServletRequest request) {
        //获取参数
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //从seesion中获取之前存入的验证码
        //String sessionCode = (String) request.getSession().getAttribute("code");
        //从Redis中获取之前存入的验证码
        String redisCode = (String) redisTemplate.opsForValue().get(phone);
        //校验验证码
        if (redisCode != null && redisCode.equals(code)) {
            //根据手机号查询User表
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone);
            User user = userService.getOne(wrapper);
            //如果用户不存在
            if (user == null) {
                //创建一个新用户（注册）
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                //执行保存
                userService.save(user);
            }
            //将用户信息存入到seesion中
            request.getSession().setAttribute("userId", user.getId());
            //删除Redis中的验证码
            redisTemplate.delete(phone);
            //返回用户信息
            return R.sucess(user);
        } else {
            return R.error("验证码错误");
        }
    }

    //退出登录
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("userId");
        System.out.println("hellogit");
        System.out.println("你好油桃！");
        return R.sucess("退出成功");
    }
}
